<script setup>
import { ref, onMounted, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { useOrderStore } from '@/stores/orderStore'
import AlertNotification from '@/components/AlertNotification.vue'

const orderStore = useOrderStore()
const alertRef = ref(null)
const loading = ref(false)
const tableData = ref([])
const searchQuery = ref('')

// 获取订单数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await orderStore.fetchOrders()
    tableData.value = res
  } catch (e) {
    console.error('获取数据失败:', e)
    alertRef.value?.showAlert('获取订单数据失败', 'error')
  } finally {
    loading.value = false
  }
}

// computed计算属性搜索后的表格数据
const filteredTableData = computed(() => {
  if (!searchQuery.value) {
    return tableData.value
  }
  return tableData.value.filter(order => 
    order.orderNo.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 搜索框清空
const handleSearchClear = () => {
  searchQuery.value = ''
}

onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="page-container">
    <alert-notification ref="alertRef"/>

    <el-card class="main-card">
      <!-- 搜索区域 -->
      <div class="operation-area">
        <el-input
            v-model="searchQuery"
            placeholder="请输入订单号搜索"
            style="width: 200px"
            clearable
            @clear="handleSearchClear"
        >
          <template #suffix>
            <el-icon class="el-input__icon">
              <Search />
            </el-icon>
          </template>
        </el-input>
      </div>

      <!-- 表格区域 -->
      <el-table :data="filteredTableData" border v-loading="loading">
        <el-table-column prop="orderNo" label="订单号" align="center" width="180" />
        <el-table-column prop="customerName" label="客户名称" align="center" width="120" />
        <el-table-column prop="amount" label="订单金额" align="center" width="120">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'pending' ? 'warning' : 'success'">
              {{ row.status === 'pending' ? '待处理' : '已完成' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" min-width="180" />
      </el-table>
    </el-card>
  </div>
</template>

<style scoped>
.page-container {
  padding: 20px;
}

.operation-area {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount-text {
  color: #f56c6c;
}

.el-icon {
  margin-right: 4px;
}
</style> 